package com.danger.Util;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.Map;

/**
 * Created by danger on 2016/4/6.
 */
public class FileCacheService {

    private Context context;

    public FileCacheService(Context context) {
        this.context = context;
    }

    /**
     * 保存文件
     *
     * @param fileName
     * @param map
     * @return
     */
    public boolean saveSharePreference(String fileName, Map<String, Object> map) {
        boolean flag = false;
        SharedPreferences preferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object object = entry.getValue();
            if (object instanceof Boolean) {
                Boolean b = (Boolean) object;
                editor.putBoolean(key, b);
            } else if (object instanceof Integer) {
                Integer integer = (Integer) object;
                editor.putInt(key, integer);
            } else if (object instanceof Float) {
                Float f = (Float) object;
                editor.putFloat(key, f);
            } else if (object instanceof Long) {
                Long l = (Long) object;
                editor.putLong(key, l);
            } else if (object instanceof String) {
                String str = (String) object;
                editor.putString(key, str);
            }
        }
        flag = editor.commit();
        return flag;
    }

    /**
     * 读取文件
     *
     * @param fileName
     * @return
     */
    public Map<String, ?> getSharePreference(String fileName) {
        Map<String, ?> map = null;
        SharedPreferences preferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        map = preferences.getAll();
        return map;
    }
}
